package com.yinhe.music.yhmusic.base;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.socialize.UMShareAPI;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.AppCache;
import com.yinhe.music.yhmusic.listener.OnPlayerEventListener;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.login.LoginRegisterActivity;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.music.PlayQueueFragment;
import com.yinhe.music.yhmusic.music.QuickControlsFragment;
import com.yinhe.music.yhmusic.service.PlayService;
import com.yinhe.music.yhmusic.utils.StatusBarUtil;
import com.yinhe.music.yhmusic.utils.SystemUtils;
import com.yinhe.music.yhmusic.utils.permission.PermissionReq;

import java.lang.reflect.Field;


/**
 * 基类<br>
 * 如果继承本类，需要在 layout 中添加 {@link Toolbar} ，并将 AppTheme 继承 Theme.AppCompat.NoActionBar 。
 *
 * @author wcy
 * @date 2015/11/26
 */
public abstract class BaseActivity extends AppCompatActivity
        implements OnPlayerEventListener, IServiceConnect {
    public final String TAG = getClass().getSimpleName();

    protected PlayService mService;
    protected Handler mHandler = new Handler(Looper.getMainLooper());

    QuickControlsFragment mPlayFragment;
    PlayQueueFragment playQueueFragment = new PlayQueueFragment();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtil.setStatusBarTranslucent(this, true);
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: " + getClass().getSimpleName());
        bindService();
        PushAgent.getInstance(this).onAppStart();
        AppCache.addToStack(this);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }

    /**
     * 初始化 Toolbar
     */
    protected void setToolbar(String text) {
        Toolbar mToolbar = findViewById(R.id.toolbar);

        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
            TextView title = findViewById(R.id.toolbar_title);
            title.setText(text);
            mToolbar.setTitle("");
        }

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setTitle("");
        }
    }


    /**
     * 返回按钮
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public View getView(int layout, View view) {
        return getLayoutInflater().inflate(layout, (ViewGroup) view.getParent(), false);
    }

    public void startHome() {
        startActivity(new Intent(this, LoginRegisterActivity.class));
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (mPlayFragment != null && mPlayFragment.isInitialized()) mPlayFragment.updateState();

//        if (mService == null) {
//            return;
//        }
//
//        if (mService.getPlayingMusic() == null) {
//            showQuickControl(false);
//        } else {
//            showQuickControl(true);
//        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy: " + getClass().getSimpleName());
        AppCache.removeFromStack(this);
        if (mService != null) mService.removePlayEventListner(this);
        unBindService();
        mHandler.removeCallbacksAndMessages(null);
        fixInputMethodManagerLeak(this);
        super.onDestroy();
    }

    @Override
    public void finish() {
        unBindService();
        super.finish();
    }

    /**
     * 显示软键盘
     *
     * @param editText 输入框
     */
    public void showSoftKeyboard(final EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        mHandler.postDelayed(() ->{
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }, 200L);
    }

    /**
     * 关闭软键盘
     */
    public void hideSoftKeyboard() {
        if (getCurrentFocus() != null) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 防止输入软键盘内存泄漏
     *
     * @param destContext context
     */
    public static void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
        Field f = null;
        Object obj_get = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                } // author: sodino mail:sodino@qq.com
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
//                        if (QLog.isColorLevel()) {
//                            QLog.d(ReflecterHelper.class.getSimpleName(), QLog.CLR, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext()+" dest_context=" + destContext);
//                        }
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    /**
     * 显示音乐控制栏
     *
     * @param show 状态
     */
    protected void showQuickControl(boolean show) {
        FrameLayout controlLayout = findViewById(R.id.bottom_container);
        if (controlLayout == null) {
            return;
        }
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (mPlayFragment == null) {
            mPlayFragment = QuickControlsFragment.newInstance();
            ft.add(R.id.bottom_container, mPlayFragment).commitAllowingStateLoss();
        }
        if (show) {
            controlLayout.setVisibility(View.VISIBLE);
            ft.show(mPlayFragment);
        } else {
            controlLayout.setVisibility(View.GONE);
            ft.hide(mPlayFragment);
        }
    }

    /**
     * 显示播放列表
     */
    public void showPlayingList() {
        playQueueFragment.show(getSupportFragmentManager(), "playlistframent");
    }

    @Override
    public void onPublish(int progress) {
        if (mPlayFragment != null && mPlayFragment.isInitialized()) {
            mPlayFragment.onPublish(progress);
        }
    }

    @Override
    public void onChange(Music music) {
        if (music == null) {
            return;
        }
        if (mPlayFragment != null && mPlayFragment.isInitialized()) {
            mPlayFragment.updateTrackInfo(music);
        }

    }

    @Override
    public void onPlayerPause() {
        if (mPlayFragment != null && mPlayFragment.isInitialized()) {
            mPlayFragment.updateState();
        }
    }

    @Override
    public void onPlayerResume() {
        if (mPlayFragment != null && mPlayFragment.isInitialized()) {
            mPlayFragment.updateState();
        }
    }

    /**
     * 格式化时间
     *
     * @param time 原始时间
     * @return 格式化后时间
     */
    public String formatTime(long time) {
        return SystemUtils.formatTime("mm:ss", time);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private ServiceConnection servConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((PlayService.PlayBinder) service).getService();
            BaseActivity.this.onServiceConnected(mService);
            mService.addOnPlayEventListener(BaseActivity.this);

//            if (mService.getPlayingMusic() == null) {
//                showQuickControl(false);
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            BaseActivity.this.onServiceDisconnected();

        }
    };

    @Override
    public void bindService() {
        if (servConn == null) return;
        Intent intent = new Intent();
        intent.setClass(this, PlayService.class);
        bindService(intent, servConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void unBindService() {
        if (servConn != null) {
            unbindService(servConn);
            servConn = null;
        }
    }

    /**
     * 建立与Service连接回调
     *
     * @param service 绑定的服务
     */
    public void onServiceConnected(PlayService service) {
        MLog.info(TAG, "onServiceConnected");
    }

    /**
     * 与服务丢失连接时回调
     */
    public void onServiceDisconnected() {
        MLog.info(TAG, "onServiceDisconnected");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionReq.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
